#/usr/bin/perl                                                                                                                           
use POSIX "fmod"; # float modulus
use List::Util qw[min]; # min function

# Threshold for significant presence 1% of the grid = 1000 crypts
$frequency_threshold = 0.01;

# Seed the random number generator
srand (0);

# Do simulation results file globbing
$outputdir = "/home/rumen/simulation1";
#$query = "K=0_P=0.25_MU=1e-06_NU=1e-05_RSM=1_B=0.02_D=0.016_NN=100_T=7300_H=300_W=300";
$query = "T=7300";

# Get all sweeps that match the query
opendir(DIR, $outputdir);
@files = grep { /$query/ } readdir(DIR);
closedir(DIR);

foreach $f (@files) {
    print STDERR "Processing sweep $f...\n";
    $dir = $outputdir."/".$f;    
    opendir(DIR, $dir);    
    @infiles = grep { /rep(\d+)\.log/ } readdir(DIR);
    closedir(DIR);
    
    # Contains all the rep runs number, e.g. if rep45, rep3, rep1 are present, rephash stores 45, 3, 1
    my %rephash = ();   
    foreach $i (@infiles) {
	@repnumber = split (/rep|\./, $i);
	$rephash{$repnumber[1]}=1;
    }

    foreach $run (keys %rephash){
	# The name of the run:
	compute_fitness_landscape($dir."/rep".$run);
	print STDERR "Sweep ".$dir."/rep".$run." done.\n";
    }
}


sub compute_fitness_landscape(){

    my ($runfn) = @_;

    my %cid_to_pattern = ();

    my %pattern=();
    # Load all patterns in memory
    open (in,"$runfn.patterns");
    while(<in>){
	chomp;
	@row=split(/\,/);
	# Store pattern at reproductive loci
	if(!defined($cid_to_pattern{$row[0]})){
	    $cid_to_pattern{$row[0]} = "";
	    for my $loc (101..105){
		$cid_to_pattern{$row[0]} = $cid_to_pattern{$row[0]}.$row[$loc];
	    }
	}
    }
    close in;

    my %day = ();
    my %pattern_to_count = ();
    my $firstday = 1;
    open (in,"$runfn.log");
    while(<in>){
	chomp;
	@row=split(/\,/);
	# New day
	if(!defined($day{$row[2]})){
	    %pattern_to_count = ();
	    # Store pattern at reproductive loci
	    if($h{$row[0]}){
	    }
	    # Store new day in hash
	    $day{$row[2]} = 1;
	} else {
	    
	}
    }
    close in;
}
 
